package com.springboot.testcord.controller;

import com.springboot.testcord.vo.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class uploadController {

    @Value("${web.upload-path}")
    private String uploadPath;

    @PostMapping
    public ResultVo upload(MultipartFile file){

        if (!file.isEmpty()) {
            //上传到uploadPath
            String originalFilename = file.getOriginalFilename();
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (file.getSize()>500*1024){
                throw new RuntimeException("文件过大");
            } else if (fileSuffix.equalsIgnoreCase(".jpg")||
                    fileSuffix.equalsIgnoreCase(".png")||
                    fileSuffix.equalsIgnoreCase(".jpeg")||
                    fileSuffix.equalsIgnoreCase(".gif")
            ) {
                File savePath = new File(uploadPath);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }
                //正常上传
                String fileName = UUID.randomUUID().toString().replace("-","");
                File saveFile = new File(uploadPath+fileName+fileSuffix);
                try {
                    file.transferTo(saveFile);
                    return new ResultVo(200,"上传成功",null);
                } catch (IOException e) {
                    throw new RuntimeException("文件上传异常");
                }
            }else {
                throw new RuntimeException("文件格式不对");
            }
        }else {
            throw new RuntimeException("文件必填");
        }

    }
}
